package com.example.sss.service.ArithmeticService;

import com.example.sss.dao.HeatRecordMapper;
import com.example.sss.dao.SharedFileMapper;
import com.example.sss.model.domin.*;
import com.example.sss.service.DTO.UserFilesDTO;
import com.example.sss.service.LogService.LogOperate;
import com.example.sss.service.UserService.UserService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * description
 *
 * @author tingting.wang03@hand-china.com 2021/04/15 18:08
 */
@Service
public class ArithmeticServiceImpl implements ArithmeticService{

    @Autowired
    UserService userService;
    @Autowired
    LogOperate logOperate;
    @Autowired
    SharedFileMapper sharedFileMapper;
    @Autowired
    HeatRecordMapper heatRecordMapper;

    /**
     * 协同过滤算法推荐文件
     * @param userId
     * @return
     */
    @Override
    public List<Integer> arithmetic(Integer userId){
        /**
         * 输入用户-->物品条目 一个用户对应多个物品
         * 用户ID 物品ID集合
         * A  a b d
         * B  a c
         * C  b e
         * D  c d e
         */
        List<UserFilesDTO> userFilesDTOList = new ArrayList<>();
        //查询用户
        List<User> userList = userService.selectUsersByUserid(userId);
        //查询每个用户近一周的操作文件   ->已经删除的不要
        for (User user : userList) {
            List<Integer> fileIds = logOperate.selectLogByUserId(user.getId()).stream().map(FileLog::getFileId).collect(Collectors.toList());
            if (fileIds.size()>0){
                UserFilesDTO userFilesDTO = new UserFilesDTO();
                userFilesDTO.setUser(user);
                userFilesDTO.setFileList(fileIds);
                userFilesDTOList.add(userFilesDTO);
            }
        }
        List<Integer> fileIdList = new ArrayList<>();

        //输入用户总量
        int N = userFilesDTOList.size();
        int[][] sparseMatrix = new int[N][N];
        //建立用户稀疏矩阵，用于用户相似度计算【相似度矩阵】
        Map<String, Integer> userItemLength = new HashMap<>();
        //存储每一个用户对应的不同物品总数 eg: A 3
        Map<String, Set<String>> itemUserCollection = new HashMap<>();
        //建立物品到用户的倒排表 eg: a A B
        Set<String> items = new HashSet<>();
        //辅助存储物品集合
        Map<String, Integer> userID = new HashMap<>();
        //辅助存储每一个用户的用户ID映射
        Map<Integer, String> idUser = new HashMap<>();
        for (int i = 0; i < N ; i++){
            //依次处理N个用户 输入数据 以空格间隔
            int length = userFilesDTOList.get(i).getFileList().size();
            String user_item0 = String.valueOf(userFilesDTOList.get(i).getUser().getId());
            List<Integer> user_itemj = userFilesDTOList.get(i).getFileList();
            userItemLength.put(user_item0, length);
            //eg: A 3
            userID.put(user_item0, i);
            //用户ID与稀疏矩阵建立对应关系
            idUser.put(i, user_item0);
            //建立物品--用户倒排表
            for (int j = 0; j < length; j ++){
                if(items.contains(String.valueOf(user_itemj.get(j)))){
                    //如果已经包含对应的物品--用户映射，直接添加对应的用户
                    itemUserCollection.get(String.valueOf(user_itemj.get(j))).add(user_item0);
                } else{
                    //否则创建对应物品--用户集合映射
                    items.add(String.valueOf(user_itemj.get(j)));
                    itemUserCollection.put(String.valueOf(user_itemj.get(j)), new HashSet<String>());
                    //创建物品--用户倒排关系
                    itemUserCollection.get(String.valueOf(user_itemj.get(j))).add(user_item0);
                }
            }
        }
        //计算相似度矩阵【稀疏】
        Set<Map.Entry<String, Set<String>>> entrySet = itemUserCollection.entrySet();
        Iterator<Map.Entry<String, Set<String>>> iterator = entrySet.iterator();
        while(iterator.hasNext()){
            Set<String> commonUsers = iterator.next().getValue();
            for (String user_u : commonUsers) {
                for (String user_v : commonUsers) {
                    if(user_u.equals(user_v)){
                        continue;
                    }
                    sparseMatrix[userID.get(user_u)][userID.get(user_v)] += 1;
                    //计算用户u与用户v都有正反馈的物品总数
                }
            }
        }
        String recommendUser = String.valueOf(userId);
        //计算用户之间的相似度【余弦相似性】
        //计算指定用户recommendUser的物品推荐度
        List<Integer> fileIds = new ArrayList<>();
        for (String item: items){
            //遍历每一件物品
            Set<String> users = itemUserCollection.get(item);
            //得到购买当前物品的所有用户集合
            if(!users.contains(recommendUser)){
                //如果被推荐用户没有购买当前物品，则进行推荐度计算
                double itemRecommendDegree = 0.0;
                for (String user: users){
                    if(Objects.isNull(userID.get(recommendUser))){
                        return fileIdList;
                    } else {
                        itemRecommendDegree += sparseMatrix[userID.get(recommendUser)][userID.get(user)]/Math.sqrt(userItemLength.get(recommendUser)*userItemLength.get(user));
                    }
                }
                fileIds.add(Integer.valueOf(item));
                System.out.println("The item "+item+" for "+recommendUser +"'s recommended degree:"+itemRecommendDegree);
            }
        }
        //筛选用户有权限的文件
        for (Integer id : fileIds) {
            SharedFile myFile = sharedFileMapper.isMyFile(id, userId);
            if (myFile!=null){
                fileIdList.add(id);
            }
        }
        return fileIdList;
    }

    /**
     * 热度计算排行
     * @param userId
     * @return
     */
    @Override
    public List<Integer> heatTop10(Integer userId) {
        //查询文件及记录表数据
        List<HeatRecord> heatRecords = heatRecordMapper.selectHeatRecordByUserId(userId);
        //计算
        for (HeatRecord heatRecord:heatRecords) {
            //分子
            int a = heatRecord.getHinit()+heatRecord.getHinteract();
            //分母
            //时间因子
            SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
            Date fromDate2 = null;
            Date toDate2 = null;
            try {
                fromDate2 = simpleFormat.parse(simpleFormat.format(heatRecord.getHtime()));
                toDate2 = simpleFormat.parse(simpleFormat.format(new Date()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            long from2 = fromDate2.getTime();
            long to2 = toDate2.getTime();
            int hours = (int) ((to2-from2) / (1000 * 60 * 60));
            double b = Math.pow((hours+2),1.6);
            heatRecord.setHeatValue(a/b+heatRecord.getHweight());
        }
        heatRecords = heatRecords.stream().sorted(Comparator.comparing(HeatRecord::getHeatValue).reversed()).collect(Collectors.toList());
        //返回前十的文件id
        if (heatRecords.size()>9){
            return heatRecords.subList(0,10).stream().map(HeatRecord::getFileId).collect(Collectors.toList());
        } else {
            return heatRecords.stream().map(HeatRecord::getFileId).collect(Collectors.toList());
        }
    }

    /**
     * 添加热度记录
     * @param heatRecord
     * @return
     */
    @Override
    public int addHinit(HeatRecord heatRecord) {
        //初始热度
        if (heatRecord.getHinit() != 0){
            //查询见了多少共享组
            int i = sharedFileMapper.selectSharedNum(heatRecord.getUserId());
            heatRecord.setHinit(heatRecord.getHinit()+i);
        }
        heatRecord.setHtime(new Date());
        return heatRecordMapper.addHinit(heatRecord);
    }

    @Override
    public int deleteRecord(Integer fileId) {
        return heatRecordMapper.deleteRecord(fileId);
    }

    /**
     * 增加互动值热度
     * @param heatRecord
     * @return
     */
    @Override
    public int addHinteractRecord(HeatRecord heatRecord) {
        return heatRecordMapper.addHinteractRecord(heatRecord);
    }


}